﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

using IronPython;
using IronPython.Runtime.Exceptions;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting;

namespace starpillage.Python
{
    public class PythonHost
    {
        private ScriptRuntime runtime;
        private ScriptEngine engine;
        private ScriptScope scope;

        public PythonHost()
        {
            runtime = IronPython.Hosting.Python.CreateRuntime();
            engine = runtime.GetEngine("py");
            scope = engine.CreateScope();
            runtime.LoadAssembly(typeof(System.Single).Assembly);
            runtime.LoadAssembly(typeof(System.Drawing.Color).Assembly);
            runtime.LoadAssembly(typeof(System.Windows.Forms.Keys).Assembly);
            runtime.LoadAssembly(typeof(SlimDX.Vector3).Assembly);
            runtime.LoadAssembly(typeof(starpillage.Starpillage).Assembly);
        }

        public void Run(string fileName)
        {
            try
            {
                ScriptSource source = engine.CreateScriptSourceFromFile(fileName);
                source.Execute(scope);
            }
            catch (SyntaxErrorException e)
            {
                Debug.WriteLine(string.Format("{0}({1},{2}): Syntax Error {3}: {4}",
                    Path.GetFullPath(e.SourcePath), e.Line, e.Column, e.ErrorCode, e.Message));
            }
            catch (Exception e)
            {
                Debug.WriteLine(string.Format("Script Error: {0}",
                    e.Message));
            }
        }

        public void SetVariable(string variableName, object value)
        {
            scope.SetVariable(variableName, value);
        }
    }
}
